<template>
	<view class="header">
		<view class="title">检疫信息</view>
		<uni-list>
			<view class="item">
				<uni-list-item title="检疫单位"></uni-list-item>
				<uv-input placeholder="请输入检疫单位" inputAlign="right" border="none"
					v-model="quarantineInfo.quarantineUnit"></uv-input>
			</view>
			<view class="item">
				<uni-list-item title="检疫人员"></uni-list-item>
				<uv-input placeholder="请输入检疫人员" inputAlign="right" border="none"
					v-model="quarantineInfo.quarantineStaff"></uv-input>
			</view>
			<view class="item">
				<uni-list-item title="联系电话"></uni-list-item>
				<uv-input placeholder="请输入联系电话" inputAlign="right" border="none"
					v-model="quarantineInfo.contactPhone"></uv-input>
			</view>
			<view class="item">
				<uni-list-item title="检疫地址"></uni-list-item>
				<uv-input placeholder="请输入检疫地址" inputAlign="right" border="none"
					v-model="quarantineInfo.quarantineAddress"></uv-input>
			</view>
			<view class="item">
				<uni-list-item title="检疫类型"></uni-list-item>
				<uv-input placeholder="请输入检疫类型" inputAlign="right" border="none"
					v-model="quarantineInfo.quarantineType"></uv-input>
			</view>
			<uni-list-item title="检疫结果" :rightText="quarantineResultText || '未选择'" :clickable="true"
				@click="selectQuarantineResult">
			</uni-list-item>
			<view class="item">
				<uni-list-item title="检疫证明上传"></uni-list-item>
				<uv-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
					@delete="deletePic"></uv-upload>
			</view>
			<uni-list-item title="检疫时间" :rightText="quarantineInfo.quarantineTime || '未选择'" :clickable="true"
				@click="openCalendar"></uni-list-item>
			<uv-calendar ref="calendarRef" @confirm="handleConfirm" />
		</uni-list>
		<view class="title">添加牲畜</view>
		<uni-list>
			<navigator url="/pages/management/child/components/Selection">
				<uni-list-item title="选择牲畜" :rightText="livestock.imei ? `IMEI ${livestock.imei} >` : '未选择'"
					show-arrow="true"></uni-list-item>
			</navigator>
		</uni-list>
		<view class="title1">
			<view>备注：</view>
			<textarea class="remark-input" placeholder="请输入备注信息" auto-height :maxlength="-1"
				v-model="remark"></textarea>
		</view>
		<button class="btn" @click="submitForm">提交</button>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		computed
	} from 'vue';
	import {
		addQuarantine
	} from '@/utils/api/Management.js';

	// 牲畜信息
	const livestock = ref({
		imei: '',
	});

	// 备注
	const remark = ref('');
	const calendarRef = ref(null);

	// 图片
	const fileList1 = ref([]);

	// 检疫信息
	const quarantineInfo = ref({
		quarantineUnit: '',
		quarantineStaff: '',
		contactPhone: '',
		quarantineAddress: '',
		quarantineType: '',
		quarantineResult: '',
		quarantineTime: '',
		uploadedCertificate: [] // 存储多张图片URL
	});
	// 监听子页面传递的选中牲畜事件
	onMounted(() => {
		const handleLivestockSelected = (selectedImeiList) => {
			if (selectedImeiList && selectedImeiList.length > 0) {
				livestock.value.imei = selectedImeiList.join(', '); // 多个 IMEI 用逗号分隔
				console.log('接收到选中的牲畜IMEI:', livestock.value.imei);
			} else {
				livestock.value.imei = '';
			}
		};

		uni.$on('livestockSelected', handleLivestockSelected);
		// 页面卸载时移除事件监听
		onUnmounted(() => {
			uni.$off('livestockSelected', handleLivestockSelected);
		});
	});

	// 选择检疫结果
	const selectQuarantineResult = () => {
		uni.showActionSheet({
			itemList: ['合格', '不合格'],
			success: (res) => {
				const resultList = ['0', '1'];
				quarantineInfo.value.quarantineResult = resultList[res.tapIndex];
			}
		});
	};

	const quarantineResultText = computed(() => {
	  const result = quarantineInfo.value.quarantineResult;
	  if (!result) return '未选择'; // 处理空值
	  return result === '0' ? '合格' : '不合格';
	});
	// 选择检疫时间
	const openCalendar = () => {
		calendarRef.value?.open();
	};

	const handleConfirm = (e) => {
		if (Array.isArray(e)) {
			quarantineInfo.value.quarantineTime = e[0];
		}
	};

	// 新增图片上传处理
	const afterRead = async (event) => {
		// 统一处理为数组格式
		const files = Array.isArray(event.file) ? event.file : [event.file];

		// 添加上传中状态
		files.forEach((file) => {
			fileList1.value.push({
				url: file.url,
				status: 'uploading',
				message: '上传中'
			});
		});

		// 上传所有文件
		for (let i = 0; i < files.length; i++) {
			const originalIndex = fileList1.value.length - files.length + i;

			try {
				// 上传文件到服务器
				const imageUrl = await uploadFile(files[i].url);

				// 更新文件状态为成功
				fileList1.value[originalIndex] = {
					url: imageUrl,
					status: 'success',
					message: ''
				};

				// 将图片URL添加到检疫信息中
				if (!quarantineInfo.value.uploadedCertificate.includes(imageUrl)) {
					quarantineInfo.value.uploadedCertificate.push(imageUrl);
				}

			} catch (error) {
				// 更新文件状态为失败
				fileList1.value[originalIndex] = {
					...fileList1.value[originalIndex],
					status: 'failed',
					message: '上传失败'
				};
				console.error('图片上传失败:', error);
			}
		}
	};

	// 文件上传函数
	const uploadFile = (filePath) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://8.137.157.16:9999/liveStock/public/imgUpload',
				filePath: filePath,
				name: 'file',
				formData: {},
				success: (res) => {
					try {
						const response = JSON.parse(res.data);
						if (response.code === 200) {
							// 返回完整的图片访问URL
							const fullUrl = `http://8.137.157.16:9999${response.data}`;
							resolve(fullUrl);
						} else {
							reject(new Error(response.msg || '上传失败'));
						}
					} catch (e) {
						reject(new Error('解析响应失败'));
					}
				},
				fail: (err) => {
					reject(new Error('上传请求失败'));
				}
			});
		});
	};

	// 删除图片处理
	const deletePic = (event) => {
		// 从文件列表中删除
		const deletedFile = fileList1.value.splice(event.index, 1)[0];

		// 从检疫信息中删除对应的URL
		quarantineInfo.value.uploadedCertificate =
			quarantineInfo.value.uploadedCertificate.filter(url => url !== deletedFile.url);
	};

	// 提交表单
	const submitForm = async () => {
		// 表单验证
		if (!livestock.value.imei) {
			return uni.showToast({
				title: '请选择牲畜',
				icon: 'none'
			});
		}

		if (fileList1.value.length === 0) {
			return uni.showToast({
				title: '请上传检疫证明',
				icon: 'none'
			});
		}

		// 检查是否有上传失败的图片
		const hasError = fileList1.value.some(item => item.status === 'failed');
		if (hasError) {
			return uni.showToast({
				title: '存在上传失败的图片，请重试',
				icon: 'none'
			});
		}

		const formData = {
			F_liveid: livestock.value.imei,
			F_Stand: quarantineInfo.value.quarantineUnit,
			F_Title: quarantineInfo.value.quarantineType,
			F_Phone: quarantineInfo.value.contactPhone,
			F_UserName: quarantineInfo.value.quarantineStaff,
			F_StTime: quarantineInfo.value.quarantineTime,
			F_Address: quarantineInfo.value.quarantineAddress,
			F_Level: quarantineInfo.value.quarantineResult,
			F_Remark: remark.value,
			F_ResultImage: quarantineInfo.value.uploadedCertificate.join(','),
		};
		try {
			uni.showLoading({
				title: '提交中...'
			});
			const res = await addQuarantine(formData);

			if (res.code === 200) {
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				console.log('提交成功:', res);

				// 重置表单
				livestock.value.imei = '';
				Object.keys(quarantineInfo.value).forEach(key => {
					quarantineInfo.value[key] = key === 'uploadedCertificate' ? [] : '';
				});
				remark.value = '';
				fileList1.value = [];

				// 返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);

			} else {
				uni.showToast({
					title: res.message || '提交失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('提交失败:', error);
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
</script>

<style scoped>
	.header {
		width: 100%;
		height: 95vh;
		position: relative;
		display: flex;
		flex-direction: column;
	}

	.title {
		height: 60rpx;
		width: 100%;
		background-color: #EFEFEF;
		padding-left: 20rpx;
		line-height: 60rpx;
	}

	.title1 {
		height: auto;
		width: 100%;
		padding: 20rpx;
		display: flex;
		align-items: flex-start;
	}

	.remark-input {
		flex: 1;
		min-height: 120rpx;
		padding: 10rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		line-height: 1.5;
	}

	.btn {
		width: 100%;
		height: 90rpx;
		background-color: #0BCB75;
		position: absolute;
		bottom: 0;
		color: white;
		font-size: 32rpx;
	}

	.item {
		display: flex;
		border: 2rpx solid #eee;
	}
</style>